#include "LogService.h"
#include "../../database/DatabaseUtil.h"
#include <QDateTime>
#include <QDebug>
#include <map>

LogService::LogService() {
    running = true;
    workerThread = QThread::create([this]() { processLogs(); });
    workerThread->start();
}

LogService::~LogService() {
    stop();
}

LogService &LogService::getInstance() {
    static LogService instance;
    return instance;
}

void LogService::init(bool enableConsole, const std::string &minLevel) {
    consoleOutput = enableConsole;
    minLogLevel = minLevel;
    qDebug() << "LogService initialized";
}

void LogService::stop() { {
        QMutexLocker locker(&mutex);
        running = false;
        cond.wakeAll();
    }
    if (workerThread && workerThread->isRunning()) {
        workerThread->quit();
        workerThread->wait();
    }
    delete workerThread;
    workerThread = nullptr;
}

void LogService::log(SystemLog log) {
    // 添加日志级别（若未设置）
    if (!log.logLevel.has_value()) {
        log.logLevel = "INFO";
    }

    if (!shouldLog(log.logLevel.value_or("INFO")))
        return;

    // 添加日志类型（若未设置）
    if (!log.logType.has_value()) {
        log.logType = "操作";
    }

    // 添加时间戳（若未设置）
    if (!log.timestamp.has_value()) {
        log.timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toStdString();
    }

    QMutexLocker locker(&mutex);
    logQueue.push(log);
    cond.wakeOne();
}

void LogService::processLogs() {
    while (true) {
        SystemLog log; {
            QMutexLocker locker(&mutex);
            while (logQueue.empty() && running) {
                cond.wait(&mutex);
            }
            if (!running && logQueue.empty())
                break;
            log = logQueue.front();
            logQueue.pop();
        }

        // 控制台输出
        if (consoleOutput) {
            qDebug() << "[Log]" << QString::fromStdString(log.timestamp.value_or(""))
                    << QString::fromStdString(log.logLevel.value_or(""))
                    << QString::fromStdString(log.content.value_or(""));
        }

        // 插入数据库
        DatabaseUtil &db = DatabaseUtil::getInstance();
        db.executeUpdate(R"(
            INSERT INTO system_logs (timestamp, logType, logLevel, content, userId, deviceId)
            VALUES (?, ?, ?, ?, ?, ?)
        )",
                         {
                             QString::fromStdString(log.timestamp.value_or("")),
                             QString::fromStdString(log.logType.value_or("系统")),
                             QString::fromStdString(log.logLevel.value_or("INFO")),
                             QString::fromStdString(log.content.value_or("")),
                             log.userId.value_or(-1),
                             log.deviceId.value_or(-1),
                         });
    }
}

bool LogService::shouldLog(const std::string &level) {
    static std::map<std::string, int> levelMap{
        {"DEBUG", 0}, {"INFO", 1}, {"WARNING", 2}, {"ERROR", 3}, {"CRITICAL", 4}
    };

    int curLevel = levelMap[level];
    int minLevel = levelMap[minLogLevel];
    return curLevel >= minLevel;
}
